import {
  rootPath, API, wsPath
} from "../../utils/const";
import {
  formatTime
} from "../../utils/dateUtils";
import { 
  getRequest,
  requestUserInfo
} from "../../utils/request"
import {
  getUserInfo
} from "../../utils/storageUtils";
import webSocketManager from '../../utils/webSocketManager'
// pages/home.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    deptName: '',
    userInfo: {},
    usingCount: 0,
    watiMeCount: 0,
    disinfectCount: 0,
    userRole: '',
    iconList: [],
    notifications: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    requestUserInfo();
    this.setData({
      userRole: wx.getStorageSync('loginType')
    });

    let iconList = [];
    if (this.data.userRole === 'doctor') {
      iconList = [
        {
          icon: '/public/我的档案.png', page: '/pages/sendAgreementLetter/sendAgreementLetter', text: '手术知情同意书推送',bgcolor:"#00C4AC"
        },
        {
          icon: '/public/我的档案.png', page: '/pages/checkPatientLetter/checkPatientLetter', text: '查看患者知情同意书',bgcolor:"#4BCC95"
        },
        { 
          icon: '/public/我的档案.png', page: '/pages/doctorview/doctorview', text: '风险患者',bgcolor:"#00AFC4"
        },
        {
          icon: '/public/我的档案.png', page: '/pages/postOperation/postOperation', text: '术后随访',bgcolor:"#5BD14D"
        }
      ]
    } else if (this.data.userRole === 'patient') {
      iconList = [
        {
          icon: '/public/home_icon1.png', page: '/pages/sendAgreementLetter/sendAgreementLetter', text: '手术知情同意书',bgcolor:"#00C4AC"
        },
        {
          icon: '/public/home_icon2.png', page: '/pages/checkPatientLetter/checkPatientLetter', text: '我要投诉',bgcolor:"#4BCC95"
        },
        { 
          icon: '/public/home_icon3.png', page: '/pages/complaintList/complaintList', text: '我的投诉',bgcolor:"#00AFC4"
        },
        {
          icon: '/public/home_icon4.png', page: '/pages/postOperation/postOperation', text: '术后随访',bgcolor:"#5BD14D"
        },
        {
          icon: '/public/home_icon5.png', page: '/pages/postOperation/postOperation', text: '用药提醒',bgcolor:"#23D0D9"
        },
        {
          icon: '/public/home_icon6.png', page: '/pages/postOperation/postOperation', text: '复诊提醒',bgcolor:"#77B1F2"
        }
      ]
    }

    this.setData({
      iconList: iconList
    });
    this.getAllNotifications();
    const socketUrl = wsPath + API.backendWs;
    webSocketManager.connect(socketUrl);
    webSocketManager.registerCallback('NotificationRecord', this.handleWsMessage);
  },

  getAllNotifications: function () {
    const that = this;
    const url = rootPath + API.getAllUnreadNotifications;
    let header = {};
    let token = wx.getStorageSync('token');
    let userId = wx.getStorageSync('LoginId');
    let userRole = wx.getStorageSync('loginType');
    header['authorization'] = "Bearer " + token;
    console.log(`Calling ${url}  with ${userRole} - ${userId} ... `);
    wx.request({
      url: url,
      header: header,
      data: {
          'id': Number(userId),
          'role': userRole
        },
      method: 'GET',
      timeout: 2000,
      success(res) {
        if (res.statusCode === 200) {
          console.log(res.data);
          let response = res.data;
          let notifications = that.processNotification(response);
          that.setData({
              notifications: notifications,
          })

        } else {
          console.error('Failed to fetch data from {}', url);
        }
      },
      fail(err) {
        console.error('Request failed', err);
      }
    }); 
      
  },

  handleWsMessage: function(data){
    const that = this;
    //console.log(`Get ws chat message ${JSON.stringify(data)}, start process..`); 
    let userId = Number(wx.getStorageSync('LoginId'));
    let userRole = wx.getStorageSync('loginType');
    if (data.ownerId !== userId || data.ownerRole !== userRole){
        // console.log("Not my notification, ignore...");
        return;
    }
    let notifications = []
    if (that.data.notifications){
        notifications = [...that.data.notifications, data];
    }
    else {
        notifications.push(data);
    }
    const unified = that.processNotification(notifications);
    that.setData({
        notifications: unified,
    })
  },

  processNotification: function(notifications){
    const uniqueNotificationsMap = new Map();
    const uniqueNotificationsIdMap = new Map();

    notifications.forEach(notification => {
        uniqueNotificationsIdMap.set(notification.id, notification);
    });
    console.log(uniqueNotificationsIdMap);

    // Convert the map values back to an array
    const uniqueNotifications = Array.from(uniqueNotificationsIdMap.values());

    uniqueNotifications.forEach(notification => {
      const key = `${notification.targetIdentityId}-${notification.type}`;
      // Keep the notification with the most recent timestamp if there's a duplicate
      if (!uniqueNotificationsMap.has(key) || notification.timestampepoch > uniqueNotificationsMap.get(key).timestampepoch) {
        notification.isNotificationVisible = true;
        uniqueNotificationsMap.set(key, [notification.id]);
      }
      else {
        notification.isNotificationVisible = false;
        // uniqueNotificationsMap[key].push(notification.id)
      }
    });
    // Convert the map values back to an array and sort by timestampepoch in descending order
    // const uniqueNotifications = Array.from(uniqueNotificationsMap.values());
    uniqueNotifications.sort((a, b) => b.createTimeEpoch - a.createTimeEpoch);
    console.log(uniqueNotifications);
    return uniqueNotifications;
  },

  handleIconClick: function(e) {
    const page = e.currentTarget.dataset.page;
    wx.navigateTo({
      url: page
    });
  },

  loadTime() {
    // this.setIn
    const i = setInterval(() => {

      const dateStr = formatTime(Date.now(), "YY") + "年" + formatTime(Date.now(), "MM") + "月" + formatTime(Date.now(), "DD") + "日";
      const weekStr = formatTime(Date.now(), "Week");
      const timeStr = formatTime(Date.now(), "hh-mm-ss");
      // console.log("current", dateStr, weekStr, timeStr, Date.now())
      this.setData({
        dateStr,
        weekStr,
        timeStr
      })
    }, 1000)
    this.setData({
      it: i
    })

  },
  fetchUsingCount: function () {
    getRequest(API.equipUsingCount).then(res => {
      this.setData({
        usingCount: res.count
      })
    })
  },
  fetchConfirmCount: function (params) {
    {
      getRequest(API.waitConfirmGroupCount, params).then(res => {
        this.setData({
          watiMeCount: res.count
        })
      })
    }
  },
  fetchDisfinctCount: function (params) {
    {
      getRequest(API.waitConfirmGroupCount, params).then(res => {
        this.setData({
          disinfectCount: res.count
        })
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.loadTime();
    this.getAllNotifications();
    /*
    const userInfo = getUserInfo();
    this.setData({
      userInfo,
    })
    */
  },
  onSquireItemClick: function (e) {

    const {
      path
    } = e.currentTarget.dataset;
    wx.navigateTo({
      url: path,
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    clearInterval(this.data.it)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log("unload")
    webSocketManager.unregisterCallback('NotificationRecord', this.handleWsMessage);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})